package com.jjb.www.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.hjq.base.BaseAdapter;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.view.ShapeButton;
import com.hjq.shape.view.ShapeEditText;
import com.hjq.widget.layout.WrapRecyclerView;
import com.jjb.www.R;
import com.jjb.www.app.AppActivity;
import com.jjb.www.http.api.AddPromiseLogApi;
import com.jjb.www.http.api.ReportWrongQuestionApi;
import com.jjb.www.http.api.UpdateImageApi;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.ui.adapter.AddPhotoAdapter;
import com.jjb.www.utils.CompressionUtil;
import com.jjb.www.utils.StringBufferUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 *    author : Android CRG
 *    time   : 2018/10/18
 *    desc   : 添加学习记录
 */
public class AddLearningActivity extends AppActivity implements BaseAdapter.OnItemClickListener{
    private WrapRecyclerView mRecyclerView;
    private AddPhotoAdapter adapter;
    private View mFooterView;
    /**选择图片的张数*/
    private final int mCount = 6;
    /**记录选择的数据*/
    private List<String> mData;
    private ShapeButton btnSubmit;
    private ShapeEditText mRemark;
    private List<String> listImg ;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_learning;
    }

    @Override
    protected void initView() {
        mData = new ArrayList<>();
        adapter = new AddPhotoAdapter(this);
        adapter.setOnItemClickListener(this);
        mRemark = findViewById(R.id.et_remark);
        mRecyclerView = findViewById(R.id.rv_photo_list);
        btnSubmit = findViewById(R.id.btn_submit);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));
        mRecyclerView.setAdapter(adapter);
        mFooterView = LayoutInflater.from(getContext()).inflate(R.layout.item_no_photo, mRecyclerView, false);
        mRecyclerView.addFooterView(mFooterView);
        setOnClickListener(mFooterView,btnSubmit);
    }

    @Override
    protected void initData() {

    }
    @Override
    public void onClick(View view) {
        if (view == mFooterView){
            ImageSelectActivity.start(AddLearningActivity.this,(mCount-adapter.getCount()), new ImageSelectActivity.OnPhotoSelectListener() {
                @Override
                public void onSelected(List<String> data) {
                    mData.addAll(data);
                    if (data.size() == mCount || mData.size() == mCount){
                        mRecyclerView.removeFooterView(mFooterView);
                    }
                    adapter.setData(mData);
                }
            });
        } else if (view == btnSubmit) {
            String remark = "";
            listImg = new ArrayList<>();
            if (mRemark.getText() != null) {
                remark = mRemark.getText().toString().trim();
                if (TextUtils.isEmpty(remark)) {
                    toast("请输入承诺学习内容");
                    return;
                }
            }
//            if (mData.isEmpty()){
//                toast("请上传报错照片");
//                return;
//            }
            List<File> list = new ArrayList<>();
            if (!mData.isEmpty()) {
                for (int i = 0; i < mData.size(); i++) {
                    list.add(new File(mData.get(i)));
                }
                compression(remark,list,true);
            }else {
                report(remark,"");
            }
        }
    }

    private void report(String remark, String img) {
        EasyHttp.post(this)
                .api(new AddPromiseLogApi()
                        .setContent(remark)
                        .setImg(img)
                        .setCard_book_id(getInt("card_book_id")+"")
                        .setCertificate_id(getInt("certId")+"")
                )
                .request(new HttpCallback<HttpData<AddPromiseLogApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<AddPromiseLogApi.Bean> data) {
                        toast("上报成功");
                        finish();
                    }

                    @Override
                    public void onFail(Exception e) {
                        toast(e.toString());
                    }
                });
    }

    /**
     * 压缩图片
     */
    private void compression(String remark,List<File> fileList,boolean deleteFile) {
        Luban.with(this)
                .load(fileList)
                .ignoreBy(100)
                .setTargetDir(CompressionUtil.getPath(this))
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        List<File> list = new ArrayList<>();
                        list.add(file);
                        updateImage(remark,list,deleteFile);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    /**
     * 上传图片
     */
    private void updateImage(String remark,List<File> list, boolean deleteFile) {

        for (File file:list) {
            EasyHttp.post(this)
                    .api(new UpdateImageApi()
                            .setFile(file)
                    ).request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {

                @Override
                public void onSucceed(HttpData<UpdateImageApi.Bean> data) {
                    listImg.add(data.getData().getAttach_id());
                    if (listImg.size()==mData.size()){
                        String img = StringBufferUtils.arrToStr(listImg,",");
                        report(remark,img);
                    }
                }
            });
        }

    }
    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        adapter.removeItem(position);
        if (adapter.getData() != null && adapter.getData().size() < mCount && mRecyclerView.getFooterViews().isEmpty()) {
            mRecyclerView.addFooterView(mFooterView);
        }
    }
}